<template>
    <yorha-tree-button
            v-for="(item, index) in ownerData.arr"
            :key="index"
            :id="item.id"
            :children="item.children"
            :active="item.active"
            :tag="item.tag"
            @clickBtn="clickHandler">
        {{ item.title }}
        <template #msg>{{item.msg}}</template>
    </yorha-tree-button>
</template>

<script>
export default {
    name: "YorhaTree"
}
</script>

<script setup>
import YorhaTreeButton from "./YorhaTreeButton.vue";
import {onMounted, reactive} from "vue";
let props = defineProps(['treeData','autoRead'])
let emits = defineEmits(['select','update:treeData'])
let ownerData = reactive({arr:[]})

/*
* dataOne是被复制的数组，dataTwo是要被装填的数组
* */
function handlerTreeData(dataOne) {
    let dataTwo = []
    for (let i = 0; i < dataOne.length; i++) {
        dataTwo[i] = {
            ...dataOne[i],
            active:false,
            children:!dataOne[i].children?[]:handlerTreeData(dataOne[i].children)
        }
    }
    return dataTwo
}

/*
* 点击某个按钮时候的响应事件
* */
function clickHandler(id) {
    setActive(ownerData.arr, id)
    // 修改父组件中的数据，将未读变为已读
    emits('update:treeData',ownerData.arr)
    emits('select',id)
}

/*
* 设定某个按钮是选中状态
* */
function setActive(data, id) {
    for (let i = 0; i < data.length; i++) {
        if (data[i].id == id) {
            if (props.autoRead) data[i].tag = false
            data[i].active = true
        } else {
            data[i].active = false
        }
        if (data[i].children.length >=1) setActive(data[i].children, id)
    }
}

onMounted(()=>{
    ownerData.arr = handlerTreeData(props.treeData)
})

</script>

<style scoped>

</style>